package loader;

import java.io.*;

public class MyLoader extends ClassLoader
{
    private String path;

    public MyLoader(String p){
        path = p;
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException
    {
        Class clazz = null;
        byte[] classData = loadClassData(name);
        if(classData == null)
        {
            throw new IllegalAccessError("no class found");
        }
        clazz = defineClass(name, classData, 0, classData.length);
        return clazz;
    }

    private byte[] loadClassData(String name)
    {
        String fileName = getFullName(name);
        File file = new File(path, fileName);
        InputStream is = null;
        ByteArrayOutputStream baos = null;
        if(file.exists())
        {
            try
            {
                baos = new ByteArrayOutputStream();
                is = new FileInputStream(file);
                byte[] buffer = new byte[512];
                int length = 0;
                while ((length = is.read(buffer)) > 0){
                    baos.write(buffer, 0, length);
                }
                return baos.toByteArray();
            } catch (Exception e)
            {
                try
                {
                    is.close();
                    baos.close();
                } catch (IOException e1)
                {
                    e1.printStackTrace();
                }
            }
        }
        return null;
    }

    private String getFullName(String name){
        int i = name.lastIndexOf(".");
        if(i == -1){
            return name + ".class";
        }else{
            return name.substring(i + 1) + ".class";
        }
    }
}
